// 存储页面分析结果
let pageAnalysisData = null;
let platformType = null;

// 页面加载完成后执行
window.addEventListener('load', function() {
  console.log('E-com Pilot 内容脚本已加载');
  
  // 收集页面基本信息
  const pageInfo = {
    url: window.location.href,
    title: document.title,
    domain: window.location.hostname,
    path: window.location.pathname
  };
  
  // 检测是否为电商平台
  platformType = detectEcommercePlatform();
  if (platformType) {
    pageAnalysisData = analyzeEcommercePage();
  } else {
    pageAnalysisData = analyzePageForAI();
  }
  
  // 将页面信息发送到后台脚本
  chrome.runtime.sendMessage({
    action: 'pageInfo',
    data: {
      ...pageInfo,
      platformType,
      pageData: pageAnalysisData
    }
  });
  
  // 在控制台输出调试信息
  console.log('页面信息:', {
    ...pageInfo,
    platformType,
    pageData: pageAnalysisData
  });
  
  // 监听来自侧边栏的请求
  chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    // 处理获取页面分析数据请求
    if (message.action === 'getPageAnalysis') {
      // 如果数据已经过时，重新分析
      if (document.readyState === 'complete') {
        if (platformType) {
          pageAnalysisData = analyzeEcommercePage();
        } else {
          pageAnalysisData = analyzePageForAI();
        }
      }
      
      // 返回分析数据
      sendResponse({
        success: true,
        data: {
          platformType,
          pageData: pageAnalysisData
        }
      });
    }
    
    // 返回true表示异步响应
    return true;
  });
});

// 检测是否为电商平台
function detectEcommercePlatform() {
  const domain = window.location.hostname;
  const ecommercePlatforms = [
    { name: 'taobao', domains: ['taobao.com', 'sell.taobao.com'] },
    { name: 'tmall', domains: ['tmall.com', 'sell.tmall.com'] },
    { name: 'jd', domains: ['jd.com', 'seller.jd.com'] },
    { name: 'pinduoduo', domains: ['pinduoduo.com', 'mms.pinduoduo.com'] },
    { name: 'shopee', domains: ['shopee.com', 'seller.shopee.com'] },
    { name: 'amazon', domains: ['amazon.com', 'sellercentral.amazon.com'] }
  ];
  
  for (const platform of ecommercePlatforms) {
    if (platform.domains.some(d => domain.includes(d))) {
      console.log('检测到电商平台:', platform.name);
      return platform.name;
    }
  }
  
  return null;
}

// 分析电商页面
function analyzeEcommercePage() {
  // 这里可以添加针对不同电商平台的页面分析逻辑
  // 例如，提取商品信息、价格、库存等
  
  // 示例：提取页面上的价格元素
  const priceElements = document.querySelectorAll('[class*="price"], [id*="price"], [class*="Price"], [id*="Price"]');
  const prices = Array.from(priceElements).map(el => ({
    text: el.textContent.trim(),
    element: getElementPath(el)
  }));
  
  console.log('找到价格元素:', prices);
  
  // 提取按钮元素
  const buttonElements = document.querySelectorAll('button, [type="button"], [type="submit"], [class*="btn"], [class*="Btn"]');
  const buttons = Array.from(buttonElements).map(el => ({
    text: el.textContent.trim(),
    path: getElementPath(el)
  }));
  
  // 提取表单元素
  const formElements = document.querySelectorAll('form');
  const forms = Array.from(formElements).map(form => ({
    id: form.id,
    action: form.action,
    method: form.method,
    inputs: Array.from(form.querySelectorAll('input')).map(input => ({
      type: input.type,
      name: input.name,
      id: input.id,
      value: input.value
    }))
  }));
  
  return {
    prices,
    buttons,
    forms
  };
}

// 为AI分析收集页面信息
function analyzePageForAI() {
  // 收集页面结构信息
  const headings = Array.from(document.querySelectorAll('h1, h2, h3')).map(el => ({
    level: el.tagName.toLowerCase(),
    text: el.textContent.trim(),
    path: getElementPath(el)
  }));
  
  // 收集表单信息
  const forms = Array.from(document.querySelectorAll('form')).map(form => ({
    id: form.id,
    action: form.action,
    method: form.method,
    inputs: Array.from(form.querySelectorAll('input')).map(input => ({
      type: input.type,
      name: input.name,
      id: input.id,
      value: input.value
    }))
  }));
  
  // 收集按钮信息
  const buttons = Array.from(document.querySelectorAll('button, [type="button"], [type="submit"]')).map(btn => ({
    text: btn.textContent.trim(),
    type: btn.type,
    path: getElementPath(btn)
  }));
  
  // 收集链接信息
  const links = Array.from(document.querySelectorAll('a')).slice(0, 20).map(link => ({
    text: link.textContent.trim(),
    href: link.href,
    path: getElementPath(link)
  }));
  
  // 收集图片信息
  const images = Array.from(document.querySelectorAll('img')).slice(0, 10).map(img => ({
    alt: img.alt,
    src: img.src,
    width: img.width,
    height: img.height
  }));
  
  // 收集价格相关元素
  const priceElements = document.querySelectorAll('[class*="price"], [id*="price"], [class*="Price"], [id*="Price"]');
  const prices = Array.from(priceElements).map(el => ({
    text: el.textContent.trim(),
    element: getElementPath(el)
  }));
  
  return {
    url: window.location.href,
    title: document.title,
    headings,
    forms,
    buttons,
    links,
    images,
    prices,
    html: document.documentElement.outerHTML.substring(0, 10000) // 限制HTML大小
  };
}

// 获取元素的路径
function getElementPath(element) {
  if (!element) return '';
  
  let path = '';
  let current = element;
  
  while (current && current !== document.body && current !== document.documentElement) {
    let selector = current.tagName.toLowerCase();
    
    if (current.id) {
      selector += '#' + current.id;
    } else if (current.className) {
      selector += '.' + Array.from(current.classList).join('.');
    }
    
    path = selector + (path ? ' > ' + path : '');
    current = current.parentElement;
  }
  
  return path;
} 